package com.lry.pda;


public class AttrParser {

    private Lexer lexer;
    private boolean isLegalStatement = true;
    private Register register;

    public static void main(String[] args) {
        AttrParser basicParser = new AttrParser(new Lexer());
        basicParser.statements();//1+2*3;
    }

    public AttrParser(Lexer lexer) {
        this.register = new Register();
        this.lexer = lexer;
        this.lexer.input();
        this.lexer.advance();
    }

    /*
     * statements -> 空  | expression ; statements
     */
    public void statements(){
        if(lexer.match(Lexer.EOI)){
            return;
        }
        String name = register.getName();
        expression(name);
        if(lexer.match(Lexer.SEMI)){
            lexer.advance();
            statements();
        }else{
            isLegalStatement = false;
            System.out.println("expr missing semi");
        }

        if(isLegalStatement){
            System.out.println("can recognize");
        }else{
            System.out.println("can not recognize");
        }

    }


    /*
     * expression -> term expression'
     */
    public void expression(String name){
        term(name);
        expressionPrime(name);
    }

    /*
     * term -> factor term'
     */
    public void term(String name){
        factor(name);
        termPrime(name);
    }

    /*
     * expression' -> + term expression' | '空'
     */
    public void expressionPrime(String name){
        if(lexer.match(Lexer.PLUS)){
            lexer.advance();
            String name1 = register.getName();
            term(name1);
            System.out.println(name +" += "+ name1);

            expressionPrime(name);
        }
    }

    /*
     * factor -> NUM_OR_ID | LP expression RP
     */
    public void factor(String name){
        if(lexer.match(Lexer.NUM_OR_ID)){
            System.out.println(name+" = "+lexer.yytext);
            lexer.advance();
        }else if(lexer.match(Lexer.LP)){
            lexer.advance();
            expression(name);
            if(lexer.match(Lexer.RP)){
                lexer.advance();
            }else {
                isLegalStatement = false;
                System.out.println("factor missing )");
            }
        }else{
            isLegalStatement = false;
            System.out.println("factor ilegal");
        }
    }

    /*
     * term' -> * factor term' | '空'
     */
    public void termPrime(String name){
        if(lexer.match(Lexer.TIMES)){
            lexer.advance();
            String name1 = register.getName();
            factor(name1);
            System.out.println(name +" *= "+ name1);
            termPrime(name);
        }
    }
}
